package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.SubjectAdapter;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.WanshanziliaoTask;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.PopupHelper;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class WanshanziliaoActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;

    private ClearableEditText schoolEdit;
    private TextView gradeEdit;
    //    private ClearableEditText classEidt;
    private ClearableEditText realnameEidt;
    private TextView sexEdit;

    private String mSchool;
    private String mGrade;
    //    private String mClass;
    private String mRealName;
    private String mSex;
    private PopupWindow mPopWindow;
    InputMethodManager inputMethodManager;
    private TextView skipBtn;
    private int wanshanTaskId = -1;
    private PopupHelper mGradePopWindow;
    private SubjectAdapter mGradeAdapter;

    private PopupWindow shenfenPopWindow;
    private TextView shenfenText;
    private String shenfen;
    private PopupHelper mSubjectPopWindow;
    private TextView kemu;
    private SubjectAdapter mSubjectAdapter;
    private String mSubjectNo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wanshanziliao);
        mContext = this;
        initView();
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.choose_sex, null);
        view.findViewById(R.id.nan).setOnClickListener(this);
        view.findViewById(R.id.nv).setOnClickListener(this);
        mPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setBackgroundDrawable(new ColorDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);


        mSubjectAdapter = new SubjectAdapter(mContext, 1);
        mSubjectPopWindow = new PopupHelper(mContext, mSubjectAdapter);
        mSubjectPopWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSubjectPopWindow.dismissDropDownView();
                if (position == 0) {
                    mSubjectNo = null;
                    return;
                } else {
                    mSubjectNo = String.valueOf(position - 1);
                }
                kemu.setText((String) mSubjectAdapter.getItem(position));
                mSubjectAdapter.setSelectPosition(position);
//                goodclassList.doRefresh();
            }
        });


        mGradeAdapter = new SubjectAdapter(mContext, 2);
        mGradePopWindow = new PopupHelper(mContext, mGradeAdapter);

        mGradePopWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mGradePopWindow.dismissDropDownView();
                if (position == 0) {
                    mGrade = null;
                    return;
                } else {
                    mGrade = String.valueOf(position);
                }
//                mGrade = String.valueOf(position);
                gradeEdit.setText((String) mGradeAdapter.getItem(position));
                mGradeAdapter.setSelectPosition(position);
            }
        });
    }

    private void initShenfenPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_shenfen, null);
        view.findViewById(R.id.teacher).setOnClickListener(this);
        view.findViewById(R.id.student).setOnClickListener(this);
        view.findViewById(R.id.parents).setOnClickListener(this);
        shenfenPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        shenfenPopWindow.setBackgroundDrawable(new ColorDrawable());
        shenfenPopWindow.setFocusable(true);
        shenfenPopWindow.setOutsideTouchable(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wanshanziliao_btn:
                try {
                    inputMethodManager.hideSoftInputFromWindow(WanshanziliaoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (checkInput()) {
                    doWanshanZiliao();
                }
                break;
            case R.id.skip_btn:

                break;
            case R.id.sex_edit:
                try {
                    inputMethodManager.hideSoftInputFromWindow(WanshanziliaoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mPopWindow.showAtLocation(view, Gravity.CENTER, 0, 30);
                break;
            case R.id.nan:
                mSex = "true";
                sexEdit.setText(R.string.sex_nan);
                mPopWindow.dismiss();
                break;
            case R.id.nv:
                mSex = "false";
                sexEdit.setText(R.string.sex_nv);
                mPopWindow.dismiss();
                break;
            case R.id.grade_edit:
                try {
                    inputMethodManager.hideSoftInputFromWindow(WanshanziliaoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mGradePopWindow.showDropDownView(view);
                break;
            case R.id.grade_shenfen:
                try {
                    inputMethodManager.hideSoftInputFromWindow(WanshanziliaoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                shenfenPopWindow.showAtLocation(view, Gravity.CENTER, 0, 30);
                break;
            case R.id.teacher:
                shenfenText.setText("教师");
                shenfen = "3";
                kemu.setVisibility(View.VISIBLE);
                realnameEidt.setVisibility(View.VISIBLE);
                shenfenPopWindow.dismiss();
                break;
            case R.id.parents:
                shenfenText.setText("家长");
                shenfen = "2";
                kemu.setVisibility(View.GONE);
                realnameEidt.setVisibility(View.GONE);
                shenfenPopWindow.dismiss();
                break;
            case R.id.student:
                shenfenText.setText("学生");
                shenfen = "0";
                kemu.setVisibility(View.GONE);
                realnameEidt.setVisibility(View.GONE);
                shenfenPopWindow.dismiss();
                break;

            case R.id.grade_kemu:
                try {
                    inputMethodManager.hideSoftInputFromWindow(WanshanziliaoActivity.this.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mSubjectPopWindow.showAtLocationView(view, Gravity.CENTER, 0, 30);
                break;
        }
    }

    private void doWanshanZiliao() {
        String nick = null;
        try {
            nick = (URLDecoder.decode(getEatShowApp().getmUserInfo().getNickName(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        PalLog.e("2222222222222222",nick);


        String sign = getEatShowApp().getmUserInfo().getUserSign();
        mSex = getEatShowApp().getmUserInfo().getSex();
        WanshanziliaoTask task = new WanshanziliaoTask(mSchool, shenfen,mGrade,mSubjectNo, mRealName, mSex, nick, sign);
        task.addListener(mListener);
        wanshanTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private TaskEventListener mListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            getEatShowApp().getmUserInfo().setSchoolName(mSchool);
            getEatShowApp().getmUserInfo().setBelongGrade(mGrade);
            getEatShowApp().getmUserInfo().setTrueName(mRealName);
            getEatShowApp().getmUserInfo().setSex(String.valueOf(mSex));
            getEatShowApp().getmUserInfo().setSubjectNo(mSubjectNo);
            try {
                getEatShowApp().getmUserInfo().setUserType(Integer.parseInt(shenfen));
                PalLog.e("第三方登录修改身份",Integer.parseInt(shenfen)+"");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
            finish();
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }
    };

    private boolean checkInput() {
        mSchool = schoolEdit.getText().toString();
//        mGrade = gradeEdit.getText().toString();
//        mClass = classEidt.getText().toString();
        mRealName = realnameEidt.getText().toString();
        if (ViewUtil.isNull(mSchool) || ViewUtil.isNull(mGrade) ||ViewUtil.isNull(shenfenText.getText().toString())) {
            ToastUtil.showMessage(mContext, R.string.message_not_null);
            return false;
        }

        if(kemu.getVisibility() ==View.VISIBLE){
            if( ViewUtil.isNull(kemu.getText().toString())){
                ToastUtil.showMessage(mContext, R.string.message_not_null);
                return false;
            }
        }

        if(realnameEidt.getVisibility() == View.VISIBLE){
            if(ViewUtil.isNull(mRealName)){
                ToastUtil.showMessage(mContext, R.string.message_not_null);
                return false;
            }
        }
        return true;
    }

    private void initView() {
        Intent intent = getIntent();

        schoolEdit = (ClearableEditText) findViewById(R.id.school_edit);
        if (intent != null) {
            mSchool = intent.getStringExtra("school");
            if (!TextUtils.isEmpty(mSchool)) {
                schoolEdit.setText(mSchool);
                schoolEdit.setEnabled(false);
            }
        }
        gradeEdit = (TextView) findViewById(R.id.grade_edit);
        gradeEdit.setOnClickListener(this);
//        classEidt = (ClearableEditText) findViewById(R.id.class_eidt);
        realnameEidt = (ClearableEditText) findViewById(R.id.realname_eidt);
        sexEdit = (TextView) findViewById(R.id.sex_edit);
        skipBtn = (TextView) findViewById(R.id.skip_btn);
        skipBtn.setOnClickListener(this);
        sexEdit.setOnClickListener(this);
        findViewById(R.id.wanshanziliao_btn).setOnClickListener(this);
        shenfenText = (TextView) findViewById(R.id.grade_shenfen);
        shenfenText.setOnClickListener(this);

        kemu = (TextView) findViewById(R.id.grade_kemu);
        kemu.setOnClickListener(this);

        initPopWindow();
        initShenfenPopWindow();
    }
}
